199. Binary Tree Right Side View

題目199. 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].

 分析:就是找到每層最右邊的節(jié)點
1,深搜
思路: 深搜,一個集合中存放訪問到的每層節(jié)點,在搜索的過程中,更新對應(yīng)層的最右邊節(jié)點
 public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        dfs(root,result,0);
        return result;
     }
     
     private void dfs(TreeNode root, List<Integer> result, int level){
         if(root == null){
             return;
         }
         if(result.size() == level){
             result.add(level,root.val);
         }else{
             result.set(level,root.val); 
         }
         
         dfs(root.left,result,level+1);
         dfs(root.right,result,level+1);
     }

2,利用層次遍歷

思路:利用層次遍歷, 然后每層遍歷結(jié)束后,取最右邊的節(jié)點
 public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        if(root == null){
            return result;
        }
        
        Stack<TreeNode> curLevelNodes = new Stack<TreeNode>();
        curLevelNodes.push(root);
        while(!curLevelNodes.empty()){
            TreeNode rightNode = curLevelNodes.peek();
            result.add(rightNode.val);
            Stack<TreeNode> nextLevelNodes = new Stack<TreeNode>();
            for(TreeNode node : curLevelNodes){
                if(node.left != null){
                    nextLevelNodes.add(node.left);
                }
                if(node.right != null){
                    nextLevelNodes.add(node.right);
                }
            }
          curLevelNodes = nextLevelNodes;
        }
        return result;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容