程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode -- Binary Tree Right Side View

LeetCode -- Binary Tree Right Side View

編輯:C++入門知識

LeetCode -- Binary Tree Right Side View


題目描述:






Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.


For example:
Given the following binary tree,
1 <---
/
2 3 <---

5 4 <---
You should return [1, 3, 4].






思路:
BFS,存最右邊的節點。


實現代碼:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList RightSideView(TreeNode root) {
        if(root == null){
            return new List();
        }
        
        var result = new List();
        RightView(new List(){root}, result);
        
        return result;
    }
    
    public void RightView(IList nodes, IList result)
    {
    	if(!nodes.Any()){
    		return;
    	}
        
        // add last node which is on the most right position	
    	result.Add(nodes.Last().val);
    	
    	// BFS
    	var children = new List();
    	foreach(var n in nodes){
    		var nl = Children(n);
    		if(nl.Any()){
    			children.AddRange(nl);
    		}
    	}
    	
    	RightView(children, result);
    }




private IList Children(TreeNode node){
	if(node == null){
		return new List();
	}
	
	var list = new List();
	if(node.left != null){
		list.Add(node.left);		
	}
	if(node.right != null){
		list.Add(node.right);
	}
	
	return list;
}
}


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved