zoukankan      html  css  js  c++  java
  • leetcode:Insert Node in a Binary Search Tree

    1、

    Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

    Given binary search tree as follow, after Insert node 6, the tree should be:

      2             2
     /            / 
    1   4   -->   1   4
       /             /  
      3             3   6

    2、思路:
      
    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    public class Solution {
        /**
         * @param root: The root of the binary search tree.
         * @param node: insert this node into the binary search tree
         * @return: The root of the new binary search tree.
         */
        public TreeNode insertNode(TreeNode root, TreeNode node) {
             if (root == null) {
                return node;
            }
            if (root.val > node.val) {
                root.left = insertNode(root.left, node);
            } else {
                root.right = insertNode(root.right, node);
            }
            return root;
        }
    }
     
     
    工作小总结,有错请指出,谢谢。
  • 相关阅读:
    函数指针_typedef
    网络学习_2
    网络学习_1
    字节序
    string相关总结
    C++ const用法总结
    U盘安装CentOS 7.0
    windows平台CodeBlocks MinGW C++11开发环境搭建
    关于32位windows与4GB内存的那些事儿
    开启win7系统关闭日志分析
  • 原文地址:https://www.cnblogs.com/zilanghuo/p/5287901.html
Copyright © 2011-2022 走看看